<template>


    <div>
        <div class="head" style="height: 45px;
                            display:flex;justify-content: space-between;
                            align-items: center;font-size: 17px;text-align: center;">
            <span style="margin-left: 15px;font-size: 25px;color: gray;" @click="toList">X</span>
            <span v-if="location">当前定位城市:{{store.cityName  }}</span>
            <span v-else>正在获取位置信息...</span>
            <span></span>
        </div>

        <div class="search" style="display: flex;justify-content: space-between;align-items: center;
                            background-color: #f4f4f4;height: 50px;">
            <van-search v-model="value" 
                        placeholder="输入城市名或拼音" 
                        style="margin-top: 10px;width: 95%; height: 30px;"
                        @update:model-value="modelValue"
                        :show-action="showFlag"
                        @focus="focusSearch"
                        @cancel="cancelSearch"
                      />
        </div>
        <div v-for="item in newSearchList" :key="item.cityId"
            style="margin: 20px; color: #191a1b; font-size: 13px;"
            @click="onClick($event)" >{{ item.name }}</div>

            <van-empty v-show="showEmpty" description="没有找到匹配的城市" />

        <div class="cityList" style="margin-top: 30px;" v-show="showCityList">
            
            <van-index-bar  :index-list="indexList" @select="selectIndex" >
            <div  v-for="item in newCityArr" :key="item.type">
            <van-index-anchor :index="item.type" style="color: #797d82;
                                background-color: #f4f4f4;height:30px ;"
                                ></van-index-anchor>
            <van-cell :title="data.name" v-for="data in item.list" :key="data.cityId" @click="onCityName($event)" />
            </div>
            </van-index-bar>
        </div>
    </div>
</template>

<script setup>
import { computed, onMounted, ref } from 'vue';
import listStore from "../store/index"
import router from "../router/index"
import axios from 'axios';

const value = ref("") // input
const store = listStore()

const uppercaseLetters = ref([])  //26大写字母
const newCityArr = ref([])  // 过滤后端数据形成的新数据
const showFlag = ref(false) //控制取消按钮的显示
const newSearchList = ref([])  //过滤搜索数据

const showCityList = ref(true) // 控制城市下面索引栏

const showEmpty = ref(false) // 空状态时的占位提示。

const location = ref(null);  //存储经度纬度



onMounted (async() => {
    store.bottom = false
 
   await store.getCityList()

    // 生成大写字母
    for (let i = 0; i < 26; i++) {
  uppercaseLetters.value.push(String.fromCharCode(65 + i));
}   

    //根据大写字母和拿到数据的首字母进行过滤
    for (let j = 0; j < uppercaseLetters.value.length; j++) {
     newCityArr.value.push({
        type:uppercaseLetters.value[j],
        list:store.cityList.filter((item)=>
        item.pinyin.substring(0,1).toUpperCase() === uppercaseLetters.value[j]
        )
     })
    }

    newCityArr.value = newCityArr.value.filter((item)=>item.list.length)

    // 获取用户定位
    if ('geolocation' in navigator) {
        // 使用 Geolocation API 获取位置信息
       await navigator.geolocation.getCurrentPosition(
          (position) => {
            // 当获取成功时，将位置信息存储在 location 变量中
            location.value = {
              latitude: position.coords.latitude,
              longitude: position.coords.longitude,
            };
            console.log("经度：" +location.value.latitude,"纬度：" + location.value.longitude);
            // 调用百度api
              store.getPostion(location.value.latitude,location.value.longitude)
              
          },
          (error) => {
            // 获取失败时处理错误
            console.error('获取位置失败', error);
          }
        );
      } else {
        console.error('浏览器不支持 Geolocation API');
      }

})

// 瞄点
const indexList = computed(()=>newCityArr.value.map((item)=>item.type))


// 输入框获得焦点时触发
const focusSearch = (() => {
    showFlag.value = true
})

//点击取消按钮时触发
const cancelSearch = (() => {
    showFlag.value = false
    showCityList.value = true
    showEmpty.value = false
})
// 搜索框回调
const modelValue = ((value) => {
    showCityList.value = false
    // 判断输入的value 和数据里的 name pinyin
    if(value) {
        newSearchList.value =  store.cityList.filter((item)=>{
        // console.log(item.name,item.pinyin);
        if(item.name.includes(value) || item.pinyin.includes(value)) {
            return item
        }
    })
    showEmpty.value = false
    }

    if (value === "") {
        newSearchList.value = null
        showEmpty.value = true
    }
    console.log(value);
})

// 点击索引栏的字符时触发
const selectIndex = ((index) => {
    console.log(index);
})

// 点击 x号去list
const toList = (() =>{
    if(store.toListOrCinemas) {
        router.push("/list")
    } else {
        router.push("/cinemas")
    }
   
   
})

// 搜索城市 || 点击城市 方法
const searchCityOrClickCity = ((e) =>{
    // 拿到用户搜索点击的城市名 e.target.innerHTML
    //通过拿到的城市名去获取所有城市数据的 cityId
    const res =   store.cityList.filter((item)=>{
        if(item.name === e.target.innerHTML) {
            return item
        }
    })
    // 保存城市id
    store.cityId = res[0].cityId
    console.log(store.cityId);
    store.cityName = res[0].name
    console.log(store.cityName);
    // 跳转list
    router.push("/list")
    store.bottom = true
})
// 点击 搜索后的城市
const onClick = ((e) =>{
  searchCityOrClickCity(e)
})

// 点击索引栏里面的城市
const onCityName = ((e)=>{
    searchCityOrClickCity(e)
})

</script>

<style scoped>


</style>